package com.yanshaohui.springboot.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.yanshaohui.springboot.entity.primary.UserEntity;
import com.yanshaohui.springboot.entity.secondary.AddressEntity;
import com.yanshaohui.springboot.repository.primary.UserRepository;
import com.yanshaohui.springboot.repository.secondary.AddressRepository;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

@RestController
public class AddressController {

	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private AddressRepository addressRepository;

    @ApiOperation(value="获取用户地址信息")
    @ApiImplicitParam(name = "userName", value = "用户名字", required = true,paramType="path", dataType = "String")
	@GetMapping("/userAddress/{userName}")
	public AddressEntity findUserAddress(@PathVariable("userName") String userName){
		UserEntity user = userRepository.findByUserName(userName);
		if(user!=null){
			return addressRepository.findByName(user.getAddress());	
		}else{
            return null;
		}
	}
    
	@ApiOperation(value="创建地址")
    @ApiImplicitParam(name = "address", value = "地址实体", required = true, dataType = "AddressEntity")
	@PostMapping("/address")
	public AddressEntity add(@RequestBody AddressEntity address){
		return addressRepository.saveAndFlush(address);
	}
	
    @ApiOperation(value="获取地址详细信息", notes="根据地址名来获取地址详细信息")
    @ApiImplicitParam(name = "name", value = "地址", paramType="path",required = true, dataType = "String")
	@GetMapping("/address/{name}")
	public AddressEntity findAddress(@PathVariable("name") String name){
		return addressRepository.findByName(name);
	}
	
}
